import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';

import Home from '@/pages/Home/Index.vue';

import i18n from '@/locale';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: 'demo',
        name: 'Demo',
        meta: { title: 'demo' },
        component: () => import('@/pages/Demo/Index.vue')
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,

  /**
   * 导航栏前进后退，需要开启history模式，才能生效
   */
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({ left: 0, top: 0 });
      }, 1);
    });
  }
});

router.beforeResolve((to, from, next) => {
  document.title =
    i18n.global.t(`router.${to.name as string}`) || to.meta.title || '';
  next();
});

export default router;
